#  导入依赖包
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from scipy import stats

plt.rcParams['font.sans-serif'] = ['PingFang SC', 'SimHei', 'Songti SC']
plt.rcParams['axes.unicode_minus'] = False
# 读取数据
data = pd.read_csv('../../data/processed/train_v1.csv')


# print(f'总共有{data.count()}')

# print(data.head())
# 数据分析
# 1.标签值分布分析图
def label_analyze(data):
    data = data.copy()
    label_data = data['label'].value_counts()
    print(label_data)
    plt.figure(figsize=(8, 6))
    plt.pie(x=label_data.values, labels=['未回购', '回购'], autopct='%1.1f%%')
    plt.title('用户回购分布图')
    plt.show()


def age_analyze(data):
    data = data.copy(deep=True)
    data.groupby(["merchant_id"])["label"].mean()
    merchant_repeat_buy = [rate for rate in data.groupby(["merchant_id"])["label"].mean() if rate <= 1 and rate > 0]
    plt.figure(figsize=(8, 4))
    ax = plt.subplot(1, 2, 1)
    sns.distplot(merchant_repeat_buy, fit=stats.norm)
    ax = plt.subplot(1, 2, 2)
    # 年龄分段设置
    age_map = {
        1: '0-18',
        2: '19-25',
        3: '26-30',
        4: '31-35',
        5: '36-40',
        6: '41-49',
        7: '50+',
        8: '50+'

    }
    data = data[data['age_range'].notnull()]  # 去除 NaN
    data = data[data['age_range'] >= 0]
    # 先根据 age_range 创建 age_group 字段
    data['age_group'] = data['age_range'].map(age_map)
    # print(data['age_group'].value_counts())
    # data['age_group'] = data['age_range'].replace({7: '50+', 8: '50+'})
    # 再按 age_group 分组统计平均 label
    age_data = data.groupby('age_group')['label'].mean().sort_index()
    # 绘图
    ax = plt.subplot(1, 2, 2)
    age_data.plot(kind='bar', color='skyblue', ax=ax)
    # 添加数据标签（可选）
    ax.set_title('各年龄段用户回购率')
    ax.set_xlabel('年龄段')
    ax.set_ylabel('平均回购率')
    ax.grid(axis='y', linestyle='--', alpha=0.7)
    plt.xticks(rotation=0)  # 避免文字倾斜
    plt.tight_layout()
    plt.show()


def missingdatacount(data):
    missing_counts = data.isnull().sum()
    # 计算缺失值比例
    missing_percent = (data.isnull().sum() / len(data)) * 100
    # 合并为 DataFrame 查看
    missing_data = pd.DataFrame({
        'Missing Count': missing_counts,
        'Missing Percent (%)': missing_percent
    })
    print(missing_data)


def cart_analyze(data):
    data.copy(deep=True)
    data['has_shopping_cart'] = data['shopping_cart'].apply(lambda x: 1 if x > 0 else 0)
    # print(data.head(50))
    # 按是否加购分组统计平均 label
    print(data['has_shopping_cart'].value_counts())
    cart_group = data.groupby('has_shopping_cart')['label'].mean()
    # 强制设置 index 为中文标签
    cart_group.index = ['未加入购物车', '已加入购物车']
    # 绘图
    plt.figure(figsize=(6, 4))
    cart_group.plot(kind='bar', color=['#66B2FF', '#5CD6D6'], edgecolor='black')
    # 添加百分比标签
    for i, rate in enumerate(cart_group):
        plt.text(i, rate + 0.01, f'{rate:.2%}', ha='center', va='bottom')
    plt.title('是否加购对用户回购率的影响')
    plt.xlabel('是否加购（0=未加购，1=已加购）')
    plt.ylabel('平均回购率')
    plt.xticks(rotation=0)
    plt.grid(axis='y', linestyle='--', alpha=0.7)
    plt.tight_layout()
    plt.show()


# 2.5加购转化率 = shopping_cart/(clicks+1)
data['shopping_cart_rate'] = data['shopping_cart'] / (data['clicks'] + 1)
# 2.6购买转化率 = purchases/(shopping+1)
data['purchases_rate'] = data['purchases'] / (data['shopping_cart'] + 1)
# 2.7点击购买率
data['click_purchase_rate'] = data['purchases'] / (data['clicks'] + 1)


# print(f'总共有{data.count()}')
def plot_purchases_rate_vs_label(data):
    data['purchases_rate'] = data['purchases'] / (data['shopping_cart'] + 1)
    # 按 label 分组计算平均 purchases_rate
    avg_data = data.groupby('label')['purchases_rate'].mean().reset_index()

    plt.figure(figsize=(6, 4))
    sns.barplot(x='label', y='purchases_rate', data=avg_data, palette='viridis')
    plt.title('按用户回购状态的平均购买转化率')
    plt.xlabel('是否回购 (label)')
    plt.ylabel('平均购买转化率')
    plt.xticks([0, 1], ['未回购', '回购'])
    # plt.grid(True)
    plt.tight_layout()
    plt.show()
    # 分箱数量或边界定义


def useless_shape():
    bins = [0, 0.2, 0.4, 0.6, 0.8, 1.0]
    labels = ['0-0.2', '0.2-0.4', '0.4-0.6', '0.6-0.8', '0.8-1.0']
    # 使用 pd.cut 对数据进行分箱处理
    data['purchases_rate_bin'] = pd.cut(data['purchases_rate'], bins=bins, labels=labels)
    rate_label_data = data.groupby('purchases_rate_bin')['label'].mean()
    plt.figure(figsize=(8, 5))
    rate_label_data.plot(kind='bar', color='lightblue', edgecolor='black')
    plt.title('购买转化率与用户回购率（label）的关系')
    plt.xlabel('购买转化率区间')
    plt.ylabel('平均回购率 (label)')
    plt.xticks(rotation=0)
    plt.grid(axis='y', linestyle='--', alpha=0.7)
    plt.tight_layout()
    plt.show()

def plot_avg_click_purchase_rate_by_label(data):
    # 计算每个 label 类别下的平均 click_purchase_rate
    data['click_purchase_rate'] = data['purchases'] / (data['clicks'] + 1)
    avg_data = data.groupby('label')['click_purchase_rate'].mean().reset_index()


    plt.figure(figsize=(6, 4))
    sns.barplot(x='label', y='click_purchase_rate', data=avg_data, palette='Blues')
    plt.title('不同回购状态下的平均点击购买率')
    plt.xlabel('是否回购 (label)')
    plt.ylabel('平均点击购买率')
    plt.xticks(ticks=[0, 1], labels=['未回购', '回购'])
    # plt.grid(True, linestyle='--', alpha=0.5)
    plt.tight_layout()
    plt.show()
def plot_click_purchase_rate_violin(data):
    data['click_purchase_rate'] = data['purchases'] / (data['clicks'] + 1)
    plt.figure(figsize=(6, 4))
    sns.stripplot(x='label', y='click_purchase_rate', data=data, jitter=True, alpha=0.5)
    sns.pointplot(x='label', y='click_purchase_rate', data=data, color='red', ci=None)
    plt.title('点击购买率在不同回购状态下的分布')
    plt.xlabel('是否回购 (label)')
    plt.ylabel('点击购买率')
    plt.xticks(ticks=[0, 1], labels=['未回购', '回购'])
    plt.tight_layout()
    plt.show()

def plot_avg_shopping_cart_rate_by_label(data):
    # 计算每个 label 类别下的平均 shopping_cart_rate
    data['shopping_cart_rate'] = data['shopping_cart'] / (data['clicks'] + 1)
    avg_data = data.groupby('label')['shopping_cart_rate'].mean().reset_index()

    plt.figure(figsize=(6, 4))
    sns.stripplot(x='label', y='shopping_cart_rate', data=data, jitter=True, alpha=0.5)
    sns.pointplot(x='label', y='shopping_cart_rate', data=data, color='red', ci=None)
    plt.title('加购转化率在不同回购状态下的分布')
    plt.xlabel('是否回购 (label)')
    plt.ylabel('加购转化率')
    plt.xticks(ticks=[0, 1], labels=['未回购', '回购'])
    plt.tight_layout()
    plt.show()

if __name__ == '__main__':
    data = pd.read_csv('../../data/processed/train_v1.csv')
    # age_analyze(data)
    # cart_analyze(data)
    # plot_purchases_rate_vs_label(data)
    plot_avg_shopping_cart_rate_by_label(data)